import React from 'react';
import { Avatar, Modal, Spin, Dropdown, Menu } from 'antd';
import {
  LogoutOutlined,
  LockOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { connect, history } from 'umi';
import styles from './index.<%= css %>';
import { getCookie, removeCookie } from '@/utils/cookie';

const defaultAvatar = require('@/assets/default_avatar.png');

const { confirm } = Modal;

const AvatarDropdown: React.FC = () => {
  // 处理选中的子菜单
  const handleMenu = ({ key }: { key: string }) => {
    if (key === 'logout') {
      // 退出，清空本地的token
      confirm({
        centered: true,
        icon: <ExclamationCircleOutlined />,
        content: '确定要退出登录吗？',
        okText: '确定',
        cancelText: '取消',
        onOk() {
          removeCookie('token');
          history.replace('/login');
        },
        onCancel() {},
      });
    }
  };

  const menu = (
    <Menu className={styles.menu} onClick={handleMenu}>
      <Menu.Item key="editPassword" disabled>
        <LockOutlined /> 修改密码
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout">
        <LogoutOutlined /> 退出登录
      </Menu.Item>
    </Menu>
  );

  return getCookie('token') ? (
    <>
      <Dropdown overlay={menu}>
        <span className={styles.action}>
          <Avatar
            className={styles.avatar}
            size="small"
            src={defaultAvatar}
            alt="avatar"
          />
          <span>{getCookie('userName')}</span>
        </span>
      </Dropdown>
    </>
  ) : (
    <span>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    </span>
  );
};

export default connect(() => ({}))(AvatarDropdown);
